package com.example.nonggo.view.act;

import static com.example.nonggo.Constants.LATITUDE;
import static com.example.nonggo.Constants.LONGITUDE;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.blankj.utilcode.util.ToastUtils;
import com.example.nonggo.Constants;
import com.example.nonggo.R;
import com.example.nonggo.base.BaseMvpActivity;
import com.example.nonggo.contract.LoginContract;
import com.example.nonggo.contract.OnLocationCallback;
import com.example.nonggo.databinding.ActivityMainBinding;
import com.example.nonggo.fragment.Home2Fragment;
import com.example.nonggo.fragment.HomeFragment;
import com.example.nonggo.fragment.HomeLogoutFragment;
import com.example.nonggo.model.MainModel;
import com.example.nonggo.presenter.MainPresenter;
import com.example.nonggo.utils.CustomToastUtils;
import com.example.nonggo.utils.LocationOnUtils;
import com.example.nonggo.utils.NetworkUtils;
import com.example.nonggo.viewpager.VerticalPagerAdapter;
import com.tencent.mmkv.MMKV;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Completable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * @Author Kotlin MVP Plugin
 * @Date 2025/03/01
 * @Description input description
 **/
public class MainActivity extends BaseMvpActivity<LoginContract.View, MainPresenter, ActivityMainBinding> implements LoginContract.View {

    private CountDownTimer countDownTimer;
    private final long TOTAL_TIME = 60000; // 总计时长60秒
    private final long INTERVAL = 1000;   // 间隔1秒
    private List<Fragment> fragments = new ArrayList<>();
    private ViewPager2 verticalViewPager;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001;
    private boolean isPermissionPermanentlyDenied = false;
    private OnLocationCallback locationCallback;

    @Override
    protected void onResume() {
        super.onResume();
        presenter.getLocation(MMKV.defaultMMKV().getString(LONGITUDE, "")
                ,MMKV.defaultMMKV().getString(LATITUDE, ""));
    }

    @Override
    protected void initData() {
        // 初始化回调
        locationCallback = new OnLocationCallback() {
            @Override
            public void onLocationReceived(double latitude, double longitude) {
                MMKV.defaultMMKV().putString(LATITUDE, String.valueOf(latitude));
                MMKV.defaultMMKV().putString(LONGITUDE, String.valueOf(longitude));
//                CustomToastUtils.showCustomToast("位置获取成功:"+latitude+","+longitude);
                Log.e("MainActivity", "onLocationReceived " + latitude + " " + longitude);
//                presenter.getLocation(String.valueOf(longitude),String.valueOf(latitude));
            }

            @Override
            public void onLocationError(String error) {
                Log.e("MainActivity", "error =" + error );
                ToastUtils.showShort(error);
            }
        };

        if (!LocationOnUtils.isLocationEnabled(this)){
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
            return;
        }
        // 检查权限并获取位置
        if (LocationOnUtils.checkPermissions(this)) {
            getLocation();
        } else {
            requestLocationPermission();
        }
    }

    // 获取位置
    private void getLocation() {
        // 获取最后一次已知位置
        LocationOnUtils.getLastKnownLocation(this, locationCallback);

        // 或请求实时更新（示例：GPS 提供者，每10秒或移动100米更新一次）
        // LocationUtils.requestLocationUpdates(
        //     this,
        //     LocationManager.GPS_PROVIDER,
        //     10000,
        //     100,
        //     locationCallback
        // );
    }


    // 请求定位权限
    private void requestLocationPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            // 用户之前拒绝过权限，需要解释为什么需要权限
            showPermissionExplanationDialog();
        } else {
            // 直接请求权限
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.ACCESS_COARSE_LOCATION
                    },
                    LOCATION_PERMISSION_REQUEST_CODE
            );
        }
    }
    // 显示权限解释对话框
    private void showPermissionExplanationDialog() {
        new AlertDialog.Builder(this)
                .setTitle("需要定位权限")
                .setMessage("我们需要定位权限来为您提供基于位置的服务")
                .setPositiveButton("去授权", (dialog, which) -> {
                    // 再次请求权限
                    ActivityCompat.requestPermissions(
                            MainActivity.this,
                            new String[]{
                                    Manifest.permission.ACCESS_FINE_LOCATION,
                                    Manifest.permission.ACCESS_COARSE_LOCATION
                            },
                            LOCATION_PERMISSION_REQUEST_CODE
                    );
                })
                .setNegativeButton("取消", (dialog, which) -> {
                    // 处理用户坚持拒绝的情况
                    handlePermissionDenied();
                })
                .show();
    }

    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(
            int requestCode,
            @NonNull String[] permissions,
            @NonNull int[] grantResults
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予
                getLocation();
            } else {
                // 检查用户是否勾选了 "不再询问"
                if (!ActivityCompat.shouldShowRequestPermissionRationale(
                        this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
                    isPermissionPermanentlyDenied = true;
                }
                handlePermissionDenied();
            }
        }
    }

    // 处理权限被拒绝的情况
    private void handlePermissionDenied() {
        showGoToSettingsDialog();
    }

    // 显示前往设置的对话框
    private void showGoToSettingsDialog() {
        new AlertDialog.Builder(this)
                .setTitle("需要权限")
                .setMessage("您已永久拒绝定位权限，请到设置中手动启用")
                .setPositiveButton("去设置", (dialog, which) -> {
                    // 打开应用设置页面
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivity(intent);
                })
                .setNegativeButton("取消", null)
                .show();
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        //显示开机页
        lunchDelayedTask();
        verticalViewPager = (ViewPager2) findViewById(R.id.vertical_view_pager);
    }

    @Override
    protected void initListener() {
        getBinding().includeLogin.btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 检查网络状态
                if (!NetworkUtils.isNetworkAvailable(view.getContext())) {
                    CustomToastUtils.showCustomToast("网络不可用，请检查网络连接");
                    return;
                }
                String number = getBinding().includeLogin.etLogin.getText().toString();
                String code = getBinding().includeLogin.etVerify.getText().toString();
                if (number.isEmpty()) {
                    CustomToastUtils.showCustomToast("请输入手机号码");
                    return;
                }
                if (code.isEmpty()) {
                    CustomToastUtils.showCustomToast("请输入验证码");
                    return;
                }
                if (!getBinding().includeLogin.checkBox.isChecked()) {
                    CustomToastUtils.showCustomToast("请勾选我已经阅读并同意《用户协议》");
                    return;
                }
                //登录
                presenter.login(number, code);

            }
        });
        getBinding().includeLogin.btnVerify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String number = getBinding().includeLogin.etLogin.getText().toString();
                if (number.isEmpty()) {
                    CustomToastUtils.showCustomToast("请输入手机号码");
                    return;
                }
                // 检查网络状态
                if (!NetworkUtils.isNetworkAvailable(view.getContext())) {
                    CustomToastUtils.showCustomToast("网络不可用，请检查网络连接");
                    return;
                }
                //处理获取验证码UI
                setupCountDownTimer();
                startCountDown();
                //获取验证码
                presenter.getVerCode(number);
            }
        });
        getBinding().includeLogin.checkBox.setText(chaneTextColor());
        getBinding().includeLogin.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, WebActivity.class);
                startActivity(intent);
            }
        });


    }

    @NonNull
    private static SpannableStringBuilder chaneTextColor() {
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder("我已阅读并同意《用户协议》");
        // 设置“我已阅读并同意”的颜色为黑色
        ForegroundColorSpan blackSpan = new ForegroundColorSpan(Color.BLACK);
        spannableStringBuilder.setSpan(blackSpan, 0, "我已阅读并同意".length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 设置“用户协议”的颜色为蓝色
        ForegroundColorSpan blueSpan = new ForegroundColorSpan(Color.DKGRAY);
        spannableStringBuilder.setSpan(blueSpan, "我已阅读并同意 ".length(), spannableStringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableStringBuilder;
    }


    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter(new MainModel());
    }

    @Override
    protected ActivityMainBinding getViewBinding() {
        return ActivityMainBinding.inflate(getLayoutInflater());
    }

    @Override
    public void loginSuccess() {
        getBinding().includeLogin.getRoot().setVisibility(View.GONE);
        CustomToastUtils.showCustomToast("登录成功");
        showHomeContent();
    }

    @Override
    public void loginFail() {
    }

    @Override
    public void getVerCodeSuccess() {

    }
  private void showHomeContent(){
      getBinding().verticalViewPager.setVisibility(View.VISIBLE);
      //垂直viewpager
      fragments.add(new HomeFragment());
      fragments.add(new Home2Fragment());
      fragments.add(new HomeLogoutFragment());
      VerticalPagerAdapter myAdapter=new VerticalPagerAdapter(getSupportFragmentManager(),getLifecycle(),fragments);
      verticalViewPager.setAdapter(myAdapter);


    }

    @Override
    public void getVerCodeFail() {
        resetButton();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
    // 添加窗口焦点变化监听
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }
    @SuppressLint("CheckResult")
    private void lunchDelayedTask() {
        // 使用 Completable 实现延时任务
        Completable.timer(2, java.util.concurrent.TimeUnit.SECONDS) //
                .subscribeOn(Schedulers.io()) // 在 IO 线程执行延时
                .observeOn(AndroidSchedulers.mainThread()) // 切换到主线程执行 UI 操作
                .subscribe(() -> {
                    if (MMKV.defaultMMKV().getInt(Constants.USERID, 0) != 0) {
                        //显示主页面
                        showHomeContent();
                        getBinding().includeLogin.getRoot().setVisibility(View.GONE);
                    } else {
                        getBinding().includeLogin.getRoot().setVisibility(View.VISIBLE);
                    }
                    getBinding().includeLunch.getRoot().setVisibility(View.GONE);
                }, throwable -> {


                });
    }

    private void startCountDown() {
        getBinding().includeLogin.btnVerify.setEnabled(false);  // 禁用按钮
        countDownTimer.start();        // 启动倒计时
    }

    private void resetButton() {
        getBinding().includeLogin.btnVerify.setEnabled(true);   // 启用按钮
        getBinding().includeLogin.btnVerify.setText("获取"); // 恢复原始文本
    }

    private void setupCountDownTimer() {
        if (countDownTimer != null) {
            countDownTimer.cancel();   // 防止内存泄漏
        }
        countDownTimer = new CountDownTimer(TOTAL_TIME, INTERVAL) {
            @Override
            public void onTick(long millisUntilFinished) {
                // 更新按钮文字显示剩余时间
                getBinding().includeLogin.btnVerify.setText((millisUntilFinished / 1000) + "秒后重试");
            }

            @Override
            public void onFinish() {
                resetButton();
            }
        };
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();   // 防止内存泄漏
        }
        // 停止定位更新
        LocationOnUtils.stopLocationUpdates(this, new LocationListener() {
            @Override
            public void onLocationChanged(@NonNull Location location) {

            }
        });
    }
}
